package com.cimpm.project.service.impl;

import com.cimpm.project.entity.Project;
import com.cimpm.project.entity.ProjectDetail;
import com.hby.common.callback.AutoProcessControllerPart;
import com.hby.common.entities.aspect.parameter.MapperParam;
import com.hby.common.entities.aspect.parameter.ServiceInfo;
import com.hby.common.services.Impl.mian.AutoEntityServiceImpl;
import com.hby.common.utils.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProjectServiceImpl extends AutoEntityServiceImpl<Project> {

    @Autowired
    private ProjectDetailServiceImpl projectDetailService;
    @Autowired
    private ProjectprojectDetailMapperServiceImpl projectprojectDetailMapperService;

    @Override
    public void customService(AutoProcessControllerPart autoProcessControllerPart, ServiceInfo serviceInfo) throws Throwable {
        autoProcessControllerPart.setAfterAddPartCallback(() -> {
            ProjectDetail projectDetail = projectDetailService.createEntityFromMap(ProjectDetail.class, serviceInfo.getParamConverter().getParamMap());
            projectDetailService.baseQueryAdd(projectDetail);
            projectprojectDetailMapperService.addMapper(new MapperParam(serviceInfo.getNewId(), projectDetail.getId()));
            return null;
        });
        autoProcessControllerPart.setAfterPutPartCallback(() -> {
            ProjectDetail projectDetail = projectDetailService.createEntityFromMap(ProjectDetail.class, serviceInfo.getParamConverter().getParamMap());
            Integer projectDetailId = projectprojectDetailMapperService.getSecondaryIdFromPrimaryId(serviceInfo.getParamConverter().getInt("id"));
            projectDetail.setId(projectDetailId);
            projectDetailService.baseQueryEdit(projectDetail);
            return null;
        });
        autoProcessControllerPart.setBeforeDelPartCallback(() -> {
            Integer projectDetailId = projectprojectDetailMapperService.getSecondaryIdFromPrimaryId(serviceInfo.getParamConverter().getInt("id"), false);
            projectDetailService.baseQueryDelOneById(projectDetailId);
            return null;
        });
    }

    @Override
    public void addEntityOtherToRedis(Project project) {

    }

    @Override
    public void delEntityOtherFromRedis(Project project) {

    }

    public Object getProjectTree(Map<String, Object> parameter, Integer userId, String userName) throws Throwable {
        Map<String, List<Project>> projectTree = new HashMap<>();
        List<Project> allProjects = getAllEntities();
        for (Project project : allProjects) {
            String projectType = project.getType();
            if (!projectTree.containsKey(projectType)) projectTree.put(projectType, new ArrayList<>());
            projectTree.get(projectType).add(project);
        }
        return projectTree;
    }

    public Object export(Map<String, Object> parameter, Integer userId, String userName) throws Throwable {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        List<Project> projects = getEntitiesByMap(parameter, false);
        List<Object[]> datas = new ArrayList<>();
        String title = "项目信息";

        String[] columns = new String[]{
                "项目编号"
                , "所属项目"
                , "项目名称"
                , "项目名称英文名"
                , "项目经理用户名"
                , "项目经理"
                , "主管部门"
                , "编写"
                , "项目计划开始日期"
                , "项目计划结束日期"
                , "项目结束日期"
                , "项目关闭日期"
                , "项目类型"
                , "项目程度（小、中、大型）"
                , "项目体量"
                , "项目地点"
                , "项目分组"
                , "限期"
                , "项目图标"
                , "项目图片"
                , "传真"
                , "业主"
                , "合同类型"
                , "合同金额"
                , "合同编号"
                , "合同名称"
                , "合同人ID"
                , "合同人名称"
                , "项目目标"
                , "是否采购"
                , "采购人ID"
                , "采购人名称"
                , "是否使用外币"
                , "项目描述"
                , "状态（1启用，0不启用）"
                , "创建人"
                , "创建时间"
                , "修改人"
                , "修改时间"
                , "租户编号"
                , "经度"
                , "纬度"
        };

        for (Project project : projects) {
            ProjectDetail projectDetail = projectprojectDetailMapperService.getSecondaryEntityFromPrimaryId(project.getId());
            Map<String, String> data = new HashMap<>();
            data.put("项目编号", project.getCode());
            data.put("所属项目", "");
            data.put("项目名称", project.getName());
            data.put("项目名称英文名", projectDetail.getEnName());
            data.put("项目经理用户名", "");
            data.put("项目经理", projectDetail.getManager());
            data.put("主管部门", "");
            data.put("编写", "");
            data.put("项目计划开始日期", "projectDetail.getPlanBeginDate()");
            data.put("项目计划结束日期", "projectDetail.getPlanEndDate()");
            data.put("项目结束日期", "");
            data.put("项目关闭日期", "");
            data.put("项目类型", project.getType());
            data.put("项目程度（小、中、大型）", "");
            data.put("项目体量", "");
            data.put("项目地点", "");
            data.put("项目分组", "");
            data.put("限期", "");
            data.put("项目图标", "");
            data.put("项目图片", "");
            data.put("传真", "");
            data.put("业主", "");
            data.put("合同类型", "");
            data.put("合同金额", "");
            data.put("合同编号", "");
            data.put("合同名称", "");
            data.put("合同人ID", "");
            data.put("合同人名称", "");
            data.put("项目目标", "");
            data.put("是否采购", "");
            data.put("采购人ID", "");
            data.put("采购人名称", "");
            data.put("是否使用外币", "");
            data.put("项目描述", "project.getSummary()");
            data.put("状态（1启用，0不启用）", "");
            data.put("创建人", project.getCreator());
            data.put("创建时间", project.getCreateTime());
            data.put("修改人", "");
            data.put("修改时间", "");
            data.put("租户编号", "");
            data.put("经度", projectDetail.getLatitude());
            data.put("纬度", projectDetail.getLongitude());
            Object[] objects = new Object[data.size()];
            for (int i = 0; i < columns.length; i++) {
                objects[i] = data.get(columns[i]);
            }
            datas.add(objects);
        }

        //给文件命名，随机命名
        String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13);
        //生成excel文件
        HSSFWorkbook excel = ExcelUtil.getExcel(title, columns, datas);
        //向response写入文件流
        ExcelUtil.exportExcel(response, excel, fileName);
        return null;
    }

}
